package com.wuwei.tms.utils;

import java.lang.reflect.Field;

/**
 * 利用反射
 * 传来的任意一个类的属性只要为String且满足为null或者包含相应的字符即转变为空字符串
 */
public class NullToStringUtil {
    public static <T> T noNullStringAttr(T cls){
        //通过反射拿到该对象的所有属性的数组
        Field[] declaredFields = cls.getClass().getDeclaredFields();
        if (declaredFields == null||declaredFields.length==0) {
            return cls;
        }
        else {
            for (Field declaredField : declaredFields) {
                if ("String".equals(declaredField.getType().getSimpleName())) {
                    declaredField.setAccessible(true);
                    try {
                        Object value = declaredField.get(cls);
                        String name = declaredField.getName();
                        if (value == null) {
                            declaredField.set(cls,"");
                            if (name.contains("airplane")){
                                declaredField.set(cls,"该飞机已删除");
                            }
                            if (name.contains("ById")||name.contains("operator")){
                                declaredField.set(cls,"该用户已删除");
                            }
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
            return cls;
        }
    }
}
